package com.fand.utils;

import java.math.BigDecimal;

import com.fand.dto.PaginationDto;

public class PaginationUtils {
	private static int size = 10;
	
	private static int viewNoNum = 6;
	
	public static int getSize() {
		return PaginationUtils.size;
	}
	
	public static int getViewNoNum() {
		return PaginationUtils.viewNoNum;
	}
	
	public static <T> PaginationDto<T> newPagination(final int no, final int size, final int totalSize) {
		final PaginationDto<T> pagination = new PaginationDto<T>();
		
		if (totalSize < 1) { return pagination; }
		
		pagination.setTotalSize(totalSize);
		
		if (size < 1) {
			pagination.setSize(PaginationUtils.size);
		} else {
			pagination.setSize(Math.max(size, 5));
		}
		
		// 向上取整: 1.01 = 2
		final int totalNo = new java.math.BigDecimal(totalSize)
		        .divide(new BigDecimal(pagination.getSize()), BigDecimal.ROUND_UP).toBigInteger().intValue();
		
		pagination.setTotalNo(totalNo);
		
		pagination.setFirstNo(1);
		
		pagination.setNo(Math.min(Math.max(no, 1), totalNo));
		
		pagination.setHasFirstNo(pagination.getNo() > 1);
		
		pagination.setPreviousNo(Math.max(pagination.getNo() - 1, 1));
		
		pagination.setHasPreviousNo(pagination.isHasFirstNo());
		
		pagination.setNextNo(Math.min(pagination.getNo() + 1, totalNo));
		
		pagination.setHasNextNo(pagination.getNo() < pagination.getTotalNo());
		
		pagination.setLastNo(totalNo);
		
		pagination.setHasLastNo(pagination.isHasNextNo());
		
		pagination.setEndRowNum(pagination.getNo() * pagination.getSize());
		
		pagination.setBeginRowNum(pagination.getEndRowNum() - (pagination.getSize() - 1));
		
		final int viewNoNumHalf = new java.math.BigDecimal(PaginationUtils.viewNoNum)
		        .divide(new BigDecimal(2), BigDecimal.ROUND_HALF_UP).toBigInteger().intValue();
		
		int startNo = Math.max(pagination.getNo() - viewNoNumHalf, 1);
		
		final int endNo = Math.min((startNo + PaginationUtils.viewNoNum) - 1, totalNo);
		
		if (((endNo - startNo) + 1) < PaginationUtils.viewNoNum) {
			startNo = Math.max((endNo - PaginationUtils.viewNoNum) + 1, 1);
		}
		
		final int[] nos = new int[(endNo - startNo) + 1];
		
		int index = 0;
		
		while (endNo >= startNo) {
			nos[index++] = startNo++;
		}
		
		pagination.setNos(nos);
		
		return pagination;
	}
	
	public void setSize(final int size) {
		PaginationUtils.size = Math.max(size, 5);
	}
	
	public void setViewNoNum(final int viewNoNum) {
		PaginationUtils.viewNoNum = Math.max(viewNoNum, 6);
	}
}
